<?php 

class DownloadsModule extends Module {
	
	protected $models = array('DownloadCategory','Download');
	
	public function __construct() {
		parent::__construct( dirname(__FILE__) );
	}
	
	public function index() {
		$categories = $this->DownloadCategory->find( array(
			'filter' => array('SiteID' => SITE_ID)
		));
		
		$this->set(compact('categories'));
	}
	
	public function edit($id = NULL) {

		// use kan_get_parameter, so POST or GET method can be determine automatically
		if( isset($_POST['item_id']) && intval($_POST['item_id']) > 0 ) {
			$id = $_POST['item_id'];
		
			$this->autoLayout = false;
			
			// obtain the article data
			$download = $this->Download->findById($id);
			$this->set(compact('download'));
		}
		
		else if( intval($id) > 0 ) {
			// obtain the article data
			$download = $this->Download->findById($id);
			$this->set(compact('download'));
		}
		
		$categories = $this->DownloadCategory->getSiteCategories();
		$this->set(compact('categories'));
	}
	
	public function getDownloadCategory($id) {

        return $this->DownloadCategory->findFirst(array(
            'filter' => array(
                'SiteID' => SITE_ID,
                'OR' => array(
                    'id' => $id,
                    'CategoryAlias' => $id
                )
            )
        ));
    }

    /**
     *
     * @param string $siteid
     * @return array
     */
    public function getDownloadCategories($siteid = -1) {
        if ($siteid == -1 && defined("SITE_ID")) {
            $siteid = SITE_ID;
        }

        return $this->getCategories(array(
            'filter' => array("SiteID" => SITE_ID)
        ));
    }

    /**
     *
     * @param <type> $id
     * @return Download 
     */
    public function getDownload($id) {
        if (is_int(intval($id)) <= 0) {
            trigger_error("Supplied Value Is Not A Valid ID");
            return;
        }
        
        return $this->Download->findFirst( array(
            'filter' => array(
                'OR' => array(
                    'id' => $id,
                    'Alias' => $id
                )
            )
        ));
    }

    public function getDownloadByHash($hash) {

        return $this->Download->findFirst(array(
            'filter' => array("EncryptedURL" => $hash)
        ));
    }

    public function getDownloads($start = 0, $limit = NULL, $options = NULL) {

        $dOptions = array(
            'join' => array("download_categories dc" => " dc.id = Download.CategoryID AND dc.SiteID = " . SITE_ID),
			'filter' => array('Download.Published' => 1),
            'order' => 'Download.id DESC'
        );
		
		// remove filter based on published option if in the CMS
		if( defined("IN_CMS") && IN_CMS ) {
			unset($dOptions['filter']);
		}
		
        if ($options != NULL) {
            $options = array_merge($dOptions, $options);
        } else {
            $options = $dOptions;
        }

        $downloads = $this->Download->paginate($start, $limit, $options);

        return $downloads;
    }

    /**
     *
     * @return <type> 
     */
    public function addCategory() {
        if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }

        $category = new DownloadCategory(array(
            "SiteID" => SITE_ID,
            //"ParentID" => $_POST['ParentID'],
            "Position" => $_POST['Position'],
            "CategoryName" => $_POST['CategoryName'],
            "CategoryAlias" => $_POST['CategoryAlias'],
            "CategoryDescription" => $_POST['CategoryDescription']
        ));

        $category->save();

        return $category;
    }

    public function updateCategory() {
        if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }

        $category = new DownloadCategory(array(
            "id" => $_POST['id'],
            "SiteID" => SITE_ID,
            //"ParentID" => $_POST['ParentID'],
            "Position" => $_POST['Position'],
            "CategoryName" => $_POST['CategoryName'],
            "CategoryAlias" => $_POST['CategoryAlias'],
            "CategoryDescription" => $_POST['CategoryDescription']
        ));

        $category->save();

        return $category;
    }

    public function deleteDownloadCategory($id) {
        $this->deleteDownloadCategories(array($id));
    }

    public function deleteDownloadCategories($ids) {

        // include the file management class
        include( CMS_PATH . 'utils/file_utils.php');

        $categories = $this->DownloadCategory->find(array(
            'filter' => array('id IN' => $ids)
        ));

        foreach($categories as $category) {

            $category_folder = kan_fix_path("../assets/downloads/" . $category->getId() . "/");
            
            if (file_exists($category_folder)) {
                $fileUtils->rmdirr($category_folder);
            }
            
            $category->delete();
        }
    }

    /**
     * Uploads and creates a download in the database
     * 
     * @return Download the newly created download
     */
    public function addDownload() {
        if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }

        // update the destination folder for the download
        $_POST['destFolder'] = kan_fix_path($_POST['destFolder']);

        // include the CMS file uploader
        include( CMS_PATH . 'utils/fileUpload.php');

        // create an encrypted version of the file url
        $encryptedURL = md5($_POST['url']);

        // create and save a new download record
        $download = new Download(array(
            "CategoryID" => $_POST['Category'],
            "Name" => $_POST['Name'],
            "Alias" => $_POST['Alias'],
            "Description" => $_POST['Description'],
            "Thumbnail" => $_POST['Thumbnail'],
            "URL" => $_POST['url'],
            "EncryptedURL" => $encryptedURL,
            "PostDate" => date('Y-m-d')
        ));

        $download->save();

        return $download;
    }

    public function updateDownload() {
        if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }

        // create and save a new download record
        $download = new Download(array(
            "id" => $_POST['id'],
            "CategoryID" => $_POST['Category'],
            "Name" => $_POST['Name'],
            "Alias" => $_POST['Alias'],
            "Description" => $_POST['Description']
        ));

        $download->save();

        return $download;
    }

    /**
     * Deletes the download with the specified ID from the database
     *
     * @param array $ids the ID or IDs to delete, can be an array or an int
     */
    public function deleteDownload($id) {
        $this->deleteDownloads(array($id));
    }

    /**
     * Deletes the downloads with the specified ID or IDs from the database
     *
     * @param array $ids the ID or IDs to delete, can be an array or an int
     */
    public function deleteDownloads($ids) {
        if (!is_array($ids)) {
            trigger_error("Invalid Parameter Passed. Array Expected");
            return;
        }

        $downloads = $this->find('Download', array(
            'filter' => array('id IN' => $ids)
        ));

        foreach ($downloads as $download) {

            $file_path = $download->getFilePath();

            if (file_exists($file_path)) {
                @unlink($file_path);
            }
        }

        // use the manager delete items function to cut down code
        $this->deleteItems($ids);
    }

    public function publishDownload($id, $publish = true) {
        $this->publishItem($id, $publish);
    }

    public function moveDownloads($item_ids, $category_id) {
        return $this->moveItems($item_ids, $category_id);
    }

    /**
     * Renders the download controller contents to the theme file
     */
    public function render() {

        $category = NULL;
        $download = NULL;

        if (isset($_GET['category'])) {
            $category = $this->getDownloadCategory(kan_clean_input($_GET['category']));
        }

        if (isset($_GET['id'])) {
            $download = $this->getDownload(kan_clean_input($_GET['id']));
            
        } else if (isset($_GET['file'])) {
            // we are attempting a download
            $download = $this->getDownloadByHash($_GET['file']);
            $download->incrementDownloadCount();

            $exporter = new ExportManager();
            $exporter->downloadFile($download->getFilePath(), $download->getAlias());

            exit;
        } else if (isset($_GET['url'])) {
            // the url parameters
            $parts = explode("/", kan_get_parameter('url'));

            // if the url parameters contains more than two parameters then the url is
            // valid and the article can be loaded. e.g. news/article-title
            if (count($parts) >= 1 && !empty($parts[0]) && $parts[0] != "file") {
                $category = $this->getDownloadCategory(kan_clean_input($parts[0]));
            }

            if (count($parts) >= 2 && !empty($parts[1])) {
                // we are attempting a download
                if ($parts[0] == "file") {
                    $download = $this->getDownloadByHash($parts[1]);
                    $download->incrementDownloadCount();
					
					$this->Export->downloadFile($download->getFilePath(), $download->getAlias());
                    exit;
                } else {
                    $download = $this->getDownload(kan_clean_input($parts[1]));
                }
            }
        }

        $this->set("category", $category);
        $this->set("download", $download);

        parent::render();
    }
}
?>